//
//  todayViewController.m
//  weather
//
//  Created by Mfk on 12-11-13.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#define kFavorite @"favoriteList.plist"
#import "todayViewController.h"
#import "favoriteCitysViewController.h"

@interface todayViewController ()

@property (strong,nonatomic)NSMutableData *webData;
@property (copy,nonatomic)NSString *jsString;
@property (strong,nonatomic)NSURLConnection *connection;

@end

@implementation todayViewController
@synthesize webData,jsString,connection;
@synthesize waitingView;
@synthesize waiting;
@synthesize todayWeather;
@synthesize todayTemp;
@synthesize todayWind;
@synthesize todayDetail;
@synthesize todayImage;
@synthesize delegate;
@synthesize cityName;
@synthesize cityname;
@synthesize cityCode;
@synthesize cityDict;
@synthesize favoriteList;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(NSString *)dataFilePath{
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory=[paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:kFavorite];
    
}
- (IBAction)favoriteButton:(UIButton *)sender {
    NSString *city=self.navigationItem.title;
    for (id obj in self.favoriteList) {
        if([obj isEqualToString:city])
        {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"抱歉" message:@"收藏列表中已存在" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
            return;
            
        }
        
    }

    [self.favoriteList addObject:city];
    
    BOOL isdd=[self.favoriteList writeToFile:[self dataFilePath] atomically:YES];
    if(isdd){
        
        NSLog(@"true");
        NSString *title = @"提示";
        NSString *message = @"添加成功";
        
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:title message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
        

        
    }
    
}



-(void)timerOut
{
    NSString *title = @"提示";
	NSString *message = @"您当前的网络状况不佳、请检查下网络或稍后再试～";
    
	UIAlertView *alert=[[UIAlertView alloc]initWithTitle:title message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
	[alert show];
    
    
        
        //[waitingView setHidden:YES];
        //[self.waiting setHidden:YES];
    
//    if([timer isValid])
//    {
//        [timer invalidate];
//    }
    return;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [waitingView startAnimating];
    
    NSString *filepath=[self dataFilePath];
    NSLog(@"%@",filepath);
    if([[NSFileManager defaultManager]fileExistsAtPath:filepath])
    {
        NSMutableArray *array=[[NSMutableArray alloc]initWithContentsOfFile:filepath];
        self.favoriteList=array;
    }
    else {
        self.favoriteList=[[NSMutableArray alloc]init ];
    }
    
//    //启动一个定时器，10秒后触发
//    timer=[NSTimer scheduledTimerWithTimeInterval:10.0f target:self selector:@selector(timerRun) userInfo:nil repeats:YES];
    
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"雾png"]]];
    //注册一个将要进入前台的通知
    UIApplication *app=[UIApplication sharedApplication];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applicationWillEnterForeground:) name: UIApplicationWillEnterForegroundNotification object:app];
    //注册一个进入后台的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification  object:app];
    
    self.navigationController.navigationBar.barStyle=UIBarStyleBlackTranslucent;
    //设置状态栏
    
    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleBlackTranslucent];
    NSString *path=[[NSBundle mainBundle]pathForResource:@"codes" ofType:@"plist"];
    NSDictionary *dict=[[NSDictionary alloc]initWithContentsOfFile:path];
    self.cityCode=dict;
    
	
    tomorrowViewController *tomorrow=[[tomorrowViewController alloc]init];
    tomorrow.delegate=self;//设置明天的代理是今天
    //设置代理使自己
    self.delegate=self;
    //读取设置中的默认城市名称
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    self.cityName=[defaults stringForKey:@"city"];
    
    self.navigationItem.title=self.cityName;
    
    //添加一个收藏按钮
    UIBarButtonItem *favorite=[[UIBarButtonItem alloc]initWithTitle:@"收藏夹" style: UIBarButtonItemStylePlain target:self action:@selector(favoriteCitys)];
    
    self.navigationItem.leftBarButtonItem=favorite;
    [self.delegate getWeatherInfo:self.cityName];
    
}

-(void)getWeatherInfo:(NSString *)Name{
    NSLog(@"%@",Name);
    [self.waitingView setHidden:NO];
    
    NSString *code=[self.cityCode objectForKey:Name];
    NSMutableString *Url1=[[NSMutableString alloc]initWithFormat:@"http://m.weather.com.cn/data/%@.html",code];
    NSURL *url=[NSURL URLWithString:Url1];
    NSLog(@"%@",url);
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    self.connection=[NSURLConnection connectionWithRequest:request delegate:self];
    if(self.connection ==nil)
    {
        NSLog(@"创建失败");
    }
}
//显示界面上输出口的内容
-(void)weatherInfoDisplay{
        self.todayWeather.text=[self.cityDict objectForKey:@"weather1"];
        self.todayTemp.text=[self.cityDict objectForKey:@"temp1"];
        self.todayWind.text=[self.cityDict objectForKey:@"wind1"];
        self.todayDetail.text=[self.cityDict objectForKey:@"index_d"];
        
        
        
        NSString *weather=[self.cityDict objectForKey:@"weather1"];
    //根据天气状况来设置控制器的背景
        [self.delegate weatherNeedDisplay:weather toController:self];
}
//根据天气设置背景
-(void)weatherNeedDisplay:(NSString *)weather toController:(BaseViewController *)controller{
    //如果是晴天
    if (
        [weather isEqualToString:@"多云转晴"]||
        [weather isEqualToString:@"晴转多云"]||
        [weather isEqualToString:@"晴"]||
        [weather isEqualToString:@"多云"]||
        [weather isEqualToString:@"阴转晴"]||
        [weather isEqualToString:@"阴转多云"]||
        [weather isEqualToString:@"晴转阴"])
    {
        [controller.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"晴png"]]];
        self.todayTemp.textColor=[UIColor whiteColor];
        self.todayWind.textColor=[UIColor whiteColor];
    }else//如果是雾天气
        if ([weather isEqualToString:@"雾"]) {
            [controller.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"雾png"]]];
        } else//如果是雨天
            if ([weather isEqualToString:@"阴转小雨"]||
                [weather isEqualToString:@"小雨"]||
                [weather isEqualToString:@"阵雨"]||
                [weather isEqualToString:@"阵雨转小雨"]) {
                [controller.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"雨天"]]];
            }else //如果是下雪天
                if ([weather isEqualToString:@"小雪"]||
                    [weather isEqualToString:@"阵雪转晴"]||
                    [weather isEqualToString:@"多云转中雪"]||
                    [weather isEqualToString:@"中雪转阵雪"]||
                    [weather isEqualToString:@"雨夹雪"]||
                    [weather isEqualToString:@"阵雪转小雪"]||
                    [weather isEqualToString:@"晴转小雪"]||
                    [weather isEqualToString:@"阵雪"]||
                    [weather isEqualToString:@"多云转小雪"]) {
                    [controller.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"雪png"]]];
                }else//如果是阴天
                    if (
                        [weather isEqualToString:@"小雨转阴"]||
                        [weather isEqualToString:@"多云转阴"] ||
                        [weather isEqualToString:@"阴"]||
                        [weather isEqualToString:@"小雨转多云"]) {
                        [controller.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"阴png"]]];
                    }//以上都不是，选择默认背景
                    else {
                        [controller.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"city"]]];
                    }
    
    
}

//进入收藏夹
-(void)favoriteCitys{
    UIStoryboard *storyboard=[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
     favoriteCitysViewController *next=[storyboard  instantiateViewControllerWithIdentifier:@"favorite"];
    next.cityList=self.favoriteList;
    [self.navigationController pushViewController:next animated:YES];
    
}
// 程序进入前台
- (void)applicationWillEnterForeground:(NSNotification *)Notification{
    
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    [defaults synchronize];
    self.cityName=[defaults stringForKey:@"city"];
    NSLog(@"%@",self.cityName);
    [self.delegate getWeatherInfo:self.cityName];
    //NSLog(@"%@",self.cityDict);
    [self.delegate weatherInfoDisplay]; 


}
-(void)viewWillAppear:(BOOL)animated{
    //
    //[self.waiting setHidden:NO];
    //[self.delegate getWeatherInfo:self.cityName];
}
//程序进入后台
-(void)applicationDidEnterBackground:(NSNotification *)notification{
    
    //do nothing
    NSLog(@"application didEnterBackground..");
}
//在点击城市列表后调用
-(void)reload{
    
    self.cityName=self.cityname;

    self.navigationItem.title=self.cityName;
    [self.delegate getWeatherInfo:self.cityName];
    
    
    
}






	

- (void)viewDidUnload
{
    [self setTodayWeather:nil];
    [self setTodayTemp:nil];
    [self setTodayWind:nil];
    [self setTodayDetail:nil];
    [self setTodayImage:nil];
    [self setWaitingView:nil];
    [self setWaiting:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(NSDictionary *)returnWeatherInfoTo:(id)controller{
    return self.cityDict;
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
    if ([segue.identifier isEqualToString:@"gotoTomorrow"]) {
        BaseViewController *destination=segue.destinationViewController;
        if([destination respondsToSelector:@selector(setDelegate:)])
        {
            [destination setValue:self forKey:@"delegate"];
            //[destination setValue:self.cityName forKey:@"cityName"];
        }

    }
    /*if([destination respondsToSelector:@selector(setCityDict2:)])
    {
        NSDictionary *dict=[NSDictionary dictionaryWithObjectsAndKeys:self.cityDict,@"cityDict", nil];
        [destination setValue:dict forKey:@"cityDict"];
    }*/
    
    if([segue.identifier isEqualToString:@"consice"])
    {
        UITableView *controller=segue.destinationViewController;
        if([controller respondsToSelector:@selector(setDelegate:)])
        {
            [controller setValue:self forKey:@"delegate"];
        }
    }
    
    
}
#pragma mark 这是通过邮件和短信的方法
//通过邮件分享天气
- (IBAction)emailButton:(id)sender {
    
    Class mailClass=(NSClassFromString(@"MFMailComposeViewController"));
    if(mailClass !=nil)
    {
        if([mailClass canSendMail])
        {
            [self displayMailComposerSheet];
        }
        else {
			UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"通知" message:@"不能通过邮件分享" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil];
            [alert show];
            
		}
    }
}

-(void)displayMailComposerSheet{
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
	picker.mailComposeDelegate = self;
	
	[picker setSubject:@"天气通知"];
	
	
	// Set up recipients
    //发送的人
	NSArray *toRecipients = [NSArray arrayWithObject:@"first@example.com"]; 
	NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil]; 
	NSArray *bccRecipients = [NSArray arrayWithObject:@"fourth@example.com"]; 
	
	[picker setToRecipients:toRecipients];
	[picker setCcRecipients:ccRecipients];	
	[picker setBccRecipients:bccRecipients];
    
    //邮件内容
    NSString *city=[self.cityDict objectForKey:@"city"];
    NSString *temp=[self.cityDict objectForKey:@"temp1"];
    NSString *week=[self.cityDict objectForKey:@"week"];
    NSString *detail=[self.cityDict objectForKey:@"index"];
    NSString *emailBody =[NSString stringWithFormat:@"%@的天气信息\n今天%@  气温%@\n%@",city,week,temp,detail];	
	[picker setMessageBody:emailBody isHTML:NO];
	
	[self presentModalViewController:picker animated:YES];
    
}
//这是邮件的delegate方法
- (void)mailComposeController:(MFMailComposeViewController*)controller 
          didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
    
    NSString *msg=[[NSString alloc]init];
	
	// Notifies users about errors associated with the interface
	switch (result)
	{
		case MFMailComposeResultCancelled:
			msg = @"Result: Mail sending canceled";
			break;
		case MFMailComposeResultSaved:
			msg = @"Result: Mail saved";
			break;
		case MFMailComposeResultSent:
			msg = @"Result: Mail sent";
			break;
		case MFMailComposeResultFailed:
			msg = @"Result: Mail sending failed";
			break;
		default:
			msg = @"Result: Mail not sent";
			break;
	}
    
    UIAlertView *alter=[[UIAlertView alloc]initWithTitle:@"结果" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alter show];
	[self dismissModalViewControllerAnimated:YES];
    
}
//这是短信的代理方法
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller 
                 didFinishWithResult:(MessageComposeResult)result {
	
	NSString *msg=[[NSString alloc]init];
	// Notifies users about errors associated with the interface
	switch (result)
	{
		case MessageComposeResultCancelled:
			msg = @"Result: SMS sending canceled";
			break;
		case MessageComposeResultSent:
			msg = @"Result: SMS sent";
			break;
		case MessageComposeResultFailed:
			msg = @"Result: SMS sending failed";
			break;
		default:
			msg = @"Result: SMS not sent";
			break;
	}
    UIAlertView *alter=[[UIAlertView alloc]initWithTitle:@"结果" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alter show];
	[self dismissModalViewControllerAnimated:YES];
}



//这里通过短信分享  （只能在真机上调试）
- (IBAction)msgButton:(id)sender {
    
    Class messageClass=NSClassFromString(@"MFMessageComposeViewController");
    if(messageClass !=nil)
    {
        if([messageClass canSendText])
        {
            [self displaySMSComposerSheet];
        }
        else {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"不能通过短信分享" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        }
    }
    
}
-(void)displaySMSComposerSheet{
    MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
	picker.messageComposeDelegate = self;
    //短信内容
    NSString *city=[self.cityDict objectForKey:@"city"];
    NSString *temp=[self.cityDict objectForKey:@"temp1"];
    NSString *week=[self.cityDict objectForKey:@"week"];
    NSString *weather=[self.cityDict objectForKey:@"weather1"];
    //NSString *detail=[self.cityDict objectForKey:@"index"];
    NSString *SMSbody=[NSString stringWithFormat:@"这是%@的天气信息，今天%@,气温大概在%@, %@,祝您生活愉快。",city,week,temp,weather];
    picker.body=SMSbody;
    [self presentModalViewController:picker animated:YES];
    
}

#pragma mark NSURLConnectionData
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"响应下载");
    
    if(self.webData ==nil){
        self.webData =[[NSMutableData alloc]init ];
        
    }
    self.webData.length=0;
    
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    NSLog(@"正在接收数据");
    [self.webData appendData:data];
    
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    NSLog(@"这里已经接收完成");
    NSString *returnString = [[NSString alloc] initWithData:self.webData encoding:NSUTF8StringEncoding];
    self.jsString=returnString;
        NSLog(@" jsString-----------------    %@",self.jsString);
    if(self.jsString ==nil)
    {
        [self timerOut];
    }
        SBJsonParser *parser=[[SBJsonParser alloc]init];
        NSDictionary *dict=[parser objectWithString:self.jsString];
    NSLog(@"*****************	dict is   %@",dict);
        self.cityDict=[dict objectForKey:@"weatherinfo"];
        if(self.cityDict ==nil)
        {
            [self timerOut];
        }else{
            NSLog(@"*****%@*******",self.cityDict);
            [self.waitingView setHidden:YES];
            [self.waiting setHidden:YES];
            [self.delegate weatherInfoDisplay];

        }
    
    
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"--------------%@",error);
    [self timerOut];
}



@end
